package network;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UDPEchoClient {

    DatagramSocket socket=null;
    private String serverIP;//将服务器端口和IP记录下来,方便后续指定数据包发送的地址
    private int serverPort;
    public UDPEchoClient(String serverIP,int serverPort) throws SocketException {
        socket=new DatagramSocket();
        this.serverIP=serverIP;
        this.serverPort=serverPort;
    }

    public void start() throws IOException {
        System.out.println("启动客户端");
        Scanner sc=new  Scanner(System.in);
        while(true) {
            // 1. 从控制台读取用户输入
            System.out.print("->");
            String request=sc.nextLine();
            // 2. 构造一个UDP请求,发送给服务器
            DatagramPacket requestPacket=new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(this.serverIP),this.serverPort);
            socket.send(requestPacket);
            // 3. 从服务器接受到响应
            DatagramPacket responsePacket=new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);//创建一个空的DatagramPacket对象用于接受receive的返回值
            // 4. 把响应打印到控制台上
            String response=new String(responsePacket.getData(),0, responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UDPEchoClient client=new UDPEchoClient("127.0.0.1",9090);
        client.start();
    }
}
